import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface User {
  id: string;
  username: string;
  password: string;
  role: 'admin' | 'guest';
  email?: string;
  phone?: string;
  createdAt: string;
}

export const useUserStore = defineStore('user', () => {
  // 存储所有注册用户
  const users = ref<User[]>([
    // 初始化两个默认用户，与auth store中的预设账号保持一致
    {
      id: '1',
      username: 'admin',
      password: 'admin123',
      role: 'admin',
      createdAt: new Date().toISOString()
    },
    {
      id: '2',
      username: 'guest',
      password: 'guest123',
      role: 'guest',
      createdAt: new Date().toISOString()
    }
  ])

  // 注册新用户
  function registerUser(userData: Omit<User, 'id' | 'createdAt'>): boolean {
    // 检查用户名是否已存在
    const userExists = users.value.some(user => user.username === userData.username)
    if (userExists) {
      return false
    }

    // 创建新用户
    const newUser: User = {
      id: Date.now().toString(), // 简单使用时间戳作为ID
      ...userData,
      createdAt: new Date().toISOString()
    }

    // 添加到用户列表
    users.value.push(newUser)
    return true
  }

  // 获取所有用户
  function getAllUsers(): User[] {
    return users.value
  }

  // 根据用户名获取用户
  function getUserByUsername(username: string): User | undefined {
    return users.value.find(user => user.username === username)
  }

  return {
    users,
    registerUser,
    getAllUsers,
    getUserByUsername
  }
}, {
  persist: true // 持久化存储用户数据
})
